﻿'*************************************************************************
'@Tác giả : Dương Văn Thiện
'@Tên file: FrmCapQuyenNguoiDung.vb
'@Ngày tạo: 19/04/2010
'@Ngày sửa: 19/04/2010
'@Mục đích: Cấp quyền cho người dùng
'**************************************************************************
'eFrmCapQuyenNguoiDung	Cấp quyền người sử dụng
'vFrmCapQuyenNguoiDung	Cap quyen nguoi su dung
Imports Publics
Imports System.Windows.Forms
Imports DevExpress.XtraTreeList.Nodes
Imports DevExpress.XtraTreeList
Imports System.Drawing

Public Class FrmCapQuyenNguoiDung
    Private arrIDQuyen As New List(Of String)
    Private arrIDQ_Nhom As New List(Of String)
    Private objDataSource As New Collections.Generic.List(Of clsPermission)
    Private bindsource As New BindingSource
    Private _NguoiDung As DM_NhanVien
    Public Property NguoiDung() As DM_NhanVien
        Get
            Return _NguoiDung
        End Get
        Set(ByVal value As DM_NhanVien)
            _NguoiDung = value
        End Set
    End Property
    Public Function GetAllNodes(ByVal treeList As DevExpress.XtraTreeList.TreeList) As System.Collections.Generic.List(Of DevExpress.XtraTreeList.Nodes.TreeListNode)
        Return GetAllNodes(treeList.Nodes)
    End Function
    Public Function GetAllNodes(ByVal treeListNodes As DevExpress.XtraTreeList.Nodes.TreeListNodes) As System.Collections.Generic.List(Of DevExpress.XtraTreeList.Nodes.TreeListNode)
        Dim nodes As New System.Collections.Generic.List(Of DevExpress.XtraTreeList.Nodes.TreeListNode)
        For Each iNode As Nodes.TreeListNode In treeListNodes
            nodes.Add(iNode)
            If iNode.HasChildren Then
                nodes.AddRange(GetAllNodes(iNode.Nodes))
            End If
        Next
        Return nodes
    End Function
    Public Function GetCheckState(ByVal obj As Object) As CheckState
        If Not obj Is Nothing Then
            Return CType(obj, CheckState)
        End If
        Return CheckState.Unchecked
    End Function
    Public Sub SetCheckedChildNodes(ByVal node As DevExpress.XtraTreeList.Nodes.TreeListNode, ByVal check As CheckState)
        Dim i As Integer = 0
        Do While i < node.Nodes.Count
            If vUser.KiemTraQuyen(node.Nodes(i).GetValue(treMaQuyen).ToString()) Then
                If vUser.CanBo.UserName = txtTaiKhoan.Text.Trim Then
                    Return
                End If
                node.Nodes(i).Tag = check
                SetCheckedChildNodes(node.Nodes(i), check)
            ElseIf vUser.CanBo.UserName = SuperAdmin Then
                node.Nodes(i).Tag = check
                SetCheckedChildNodes(node.Nodes(i), check)
            End If
            i += 1
        Loop
    End Sub

    Public Sub SetCheckedParentNodes(ByVal node As DevExpress.XtraTreeList.Nodes.TreeListNode, ByVal check As CheckState)
        If Not node.ParentNode Is Nothing Then
            Dim b As Boolean = False
            Dim state As CheckState
            Dim i As Integer = 0
            Do While i < node.ParentNode.Nodes.Count
                If node.ParentNode.Nodes(i).Tag Is Nothing Then
                    state = CheckState.Unchecked
                Else
                    state = CType(node.ParentNode.Nodes(i).Tag, CheckState)
                End If
                If (Not check.Equals(state)) Then
                    b = Not b
                    Exit Do
                End If
                i += 1
            Loop
            If b Then
                node.ParentNode.Tag = CheckState.Indeterminate
            Else
                node.ParentNode.Tag = check
            End If
            SetCheckedParentNodes(node.ParentNode, check)
        End If
    End Sub
    Public Function GetVisibleNodes(ByVal treeList As DevExpress.XtraTreeList.TreeList) As System.Collections.Generic.List(Of DevExpress.XtraTreeList.Nodes.TreeListNode)
        Dim nodes As New System.Collections.Generic.List(Of DevExpress.XtraTreeList.Nodes.TreeListNode)
        Dim rowsInfo As DevExpress.XtraTreeList.ViewInfo.RowsInfo = treeList.ViewInfo.RowsInfo
        For Each ri As DevExpress.XtraTreeList.ViewInfo.RowInfo In rowsInfo.Rows
            nodes.Add(ri.Node)
        Next ri
        Return nodes
    End Function

    ''' <summary>
    ''' Hiển thị thông tin phím tắt trên caption của form
    ''' @NhiLV
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub GetCaptionForm()
        Dim strGhiVaDong As String = String.Empty
        Dim strThoat As String = GetStrKey(kThoat)

        If BtnGhiVaDong.Visibility = DevExpress.XtraBars.BarItemVisibility.Always And BtnGhiVaDong.Enabled = True Then
            strGhiVaDong = GetStrKey(kGhiVaDong)
        End If

        'If btnTroGiup.Visibility = DevExpress.XtraBars.BarItemVisibility.Always And btnTroGiup.Enabled = True Then
        '    strTroGiup = GetStrKey(kTroGiup)
        'End If
        Me.Text = Me.Text + strGhiVaDong + strThoat 'strTroGiup + 
    End Sub

    Private Sub FrmCapQuyenNguoiDung_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Text = "Phân quyền"
        Me.btnGhiVaDong.Caption = BtnSaveAndCloseCaption
        Me.BtnHuyBo.Caption = BtnCancelCaption
        Me.btnTroGiup.Caption = BtnHelpCaption

        Me.txtTenND.Text = NguoiDung.HoTen
        Me.txtTaiKhoan.Text = NguoiDung.UserName
        If NguoiDung.DM_DonVi IsNot Nothing Then
            Me.txtTenDV.Text = NguoiDung.DM_DonVi.TenDonVi
        End If
        Me.txtMaNguoiDung.Text = NguoiDung.MaSo


        For Each objPermission As DM_Quyen In (From ds In dbTV.DM_Quyens _
                                             Where ds.InUsed _
                                             Order By ds.ThuTu, ds.TenQuyen, ds.MaQuyen _
                                             Select ds)
            If vUser.CanBo.UserName = SuperAdmin Then
                Dim objPer As New clsPermission
                objPer.ID = objPermission.ID
                objPer.TenQuyen = objPermission.TenQuyen
                objPer.MaQuyen = objPermission.MaQuyen
                If objPermission.ParentID IsNot Nothing Then
                    objPer.ParentID = CStr(objPermission.ParentID)
                End If
                objPer.NganCam = False
                objDataSource.Add(objPer)
            Else
                If vUser.KiemTraQuyen(objPermission.MaQuyen) Then
                    Dim objPer As New clsPermission
                    objPer.ID = objPermission.ID
                    objPer.TenQuyen = objPermission.TenQuyen
                    objPer.MaQuyen = objPermission.MaQuyen
                    If objPermission.ParentID IsNot Nothing Then
                        objPer.ParentID = CStr(objPermission.ParentID)
                    End If
                    objPer.NganCam = False
                    objDataSource.Add(objPer)
                End If
            End If
        Next '
        bindsource.DataSource = objDataSource
        Me.treQuyen.DataSource = bindsource.DataSource
        Me.treQuyen.RefreshDataSource()
        Me.txtMaNguoiDung.Focus()

        ' Lấy những quyền mà người dùng đã có đánh dấu trên tree;
        ' Những quyền riêng trong bảng NGUOIDUNG_QUYEN

        Dim item As TG_NguoiDung_Quyen
        For Each item In From ds In dbTV.TG_NguoiDung_Quyens _
                         Where ds.InUsed And ds.ID_NguoiDung = NguoiDung.ID _
                         Select ds
            arrIDQuyen.Add(item.ID_Quyen)
        Next
        ' Những quyền thuộc nhóm người dùng.
        Dim items As TG_NguoiDung_Nhom_ND
        For Each items In From ds In dbTV.TG_NguoiDung_Nhom_NDs _
                          Where ds.InUsed And ds.ID_NguoiDung = NguoiDung.ID _
                          Select ds
            Dim itemq As TG_Quyen_Nhom_ND
            For Each itemq In From ds In dbTV.TG_Quyen_Nhom_NDs _
                              Where ds.InUsed And ds.ID_NhomND = items.ID_NhomND _
                              Select ds
                arrIDQ_Nhom.Add(itemq.ID_Quyen)
            Next
        Next
        If arrIDQuyen.Count > 0 Then

            arrIDQuyen = (From ds In arrIDQuyen _
                          Group Join n In arrIDQ_Nhom On ds Equals n Into qs = Group _
                          From s In qs.DefaultIfEmpty _
                          Select ds).ToList
        Else
            Dim treNode As Nodes.TreeListNode
            For Each treNode In GetAllNodes(treQuyen)
                Dim intIDQ As String = CStr(treNode.GetValue(treID))
                If arrIDQ_Nhom.Contains(intIDQ) Then
                    treNode.Tag = CheckState.Checked
                End If
            Next
        End If

        For Each treNode In GetAllNodes(treQuyen)
            Dim intIDQ As String = CStr(treNode.GetValue(treID))
            If arrIDQuyen.Contains(intIDQ) Then
                Dim obj As TG_NguoiDung_Quyen = (From ds In dbTV.TG_NguoiDung_Quyens _
                                               Where ds.InUsed And ds.ID_Quyen = intIDQ And ds.ID_NguoiDung = NguoiDung.ID _
                                               Select ds).FirstOrDefault
                If obj IsNot Nothing Then
                    If obj.NganCam Then
                        treNode.Tag = CheckState.Unchecked
                    Else
                        treNode.Tag = CheckState.Checked
                    End If
                End If
            End If
        Next
        treQuyen.Refresh()
        GetCaptionForm()
    End Sub

    Private Sub treQuyen_CellValueChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraTreeList.CellValueChangedEventArgs) Handles treQuyen.CellValueChanged

    End Sub

    Private Sub treQuyen_GetStateImage(ByVal sender As System.Object, ByVal e As DevExpress.XtraTreeList.GetStateImageEventArgs) Handles treQuyen.GetStateImage
        Dim check As CheckState = GetCheckState(e.Node.Tag)
        If check = CheckState.Unchecked Then
            e.NodeImageIndex = 0
        ElseIf check = CheckState.Checked Then
            e.NodeImageIndex = 1
        Else
            e.NodeImageIndex = 2
        End If
    End Sub

    Private Sub btnGhiVaDong_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnGhiVaDong.ItemClick
        Dim treNode As Nodes.TreeListNode
        For Each treNode In GetAllNodes(treQuyen)
            ' Lấy ID quyền
            Dim intIDQuyen = CStr(treNode.GetValue(treID))
            ' Kiểm tra xem node có được check ko, nếu trong nhóm quyền rồi thì thôi. ko thì thêm mới.
            If GetCheckState(treNode.Tag) <> CheckState.Unchecked Then
                ' Nếu không nằm trong nhóm  và ko trong tg thì thêm mới
                If Not arrIDQuyen.Contains(intIDQuyen) Then
                    Dim objtg As New TG_NguoiDung_Quyen
                    objtg.ID = CreateID()
                    objtg.ID_NguoiDung = NguoiDung.ID
                    objtg.ID_Quyen = intIDQuyen
                    objtg.NganCam = False
                    objtg.EditedOn = CDate(dbTV.GetDateTimeServer)
                    'objtg.IsSent = False
                    objtg.InUsed = True
                    dbTV.TG_NguoiDung_Quyens.InsertOnSubmit(objtg)
                End If
            Else ' Nếu trong TG_NGUOIDUNG_QUYEN đã có quyền rồi, giờ bỏ đi
                If (arrIDQuyen.Contains(intIDQuyen)) Then
                    Dim objtg As TG_NguoiDung_Quyen = (From ds In dbTV.TG_NguoiDung_Quyens _
                                                       Where ds.InUsed And ds.ID_NguoiDung = NguoiDung.ID _
                                                       And ds.ID_Quyen = intIDQuyen _
                                                       Select ds).FirstOrDefault
                    If objtg IsNot Nothing Then
                        objtg.InUsed = False
                        'objtg.IsSent = False
                        objtg.EditedOn = CDate(dbTV.GetDateTimeServer)
                    End If
                End If
            End If
        Next
        iSubmitChange()
        Me.Close()
    End Sub
    Private Sub SetCheckedNode(ByVal node As DevExpress.XtraTreeList.Nodes.TreeListNode)
        Dim check As CheckState = GetCheckState(node.Tag)
        If check = CheckState.Indeterminate OrElse check = CheckState.Unchecked Then
            check = CheckState.Checked
        Else
            check = CheckState.Unchecked
        End If
        treQuyen.BeginUpdate()
        node.Tag = check
        SetCheckedChildNodes(node, check)
        SetCheckedParentNodes(node, check)
        treQuyen.EndUpdate()
    End Sub
    Private Sub treQuyen_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles treQuyen.MouseDown        
        If e.Button = System.Windows.Forms.MouseButtons.Left Then
            Dim hInfo As DevExpress.XtraTreeList.TreeListHitInfo = treQuyen.CalcHitInfo(New Point(e.X, e.Y))
            If hInfo.HitInfoType = HitInfoType.StateImage Then
                If vUser.CanBo.UserName = SuperAdmin Then
                    SetCheckedNode(hInfo.Node)
                Else
                    If vUser.KiemTraQuyen(hInfo.Node.GetValue(treMaQuyen)) Then
                        If vUser.CanBo.UserName = txtTaiKhoan.Text.Trim Then
                            Return
                        End If
                        SetCheckedNode(hInfo.Node)
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub treQuyen_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles treQuyen.KeyUp
        treQuyen.BeginUpdate()
        If Me.treQuyen.FocusedNode IsNot Nothing Then
            Select Case e.KeyCode
                Case Keys.Right
                    Me.treQuyen.FocusedNode.Expanded = True
                Case Keys.Left
                    Me.treQuyen.FocusedNode.Expanded = False
                Case Keys.Space
                    If vUser.CanBo.UserName = SuperAdmin Then
                        SetCheckedNode(treQuyen.FocusedNode)
                    Else
                        If vUser.KiemTraQuyen(treQuyen.FocusedNode.GetValue(treMaQuyen)) Then
                            If vUser.CanBo.UserName = txtTaiKhoan.Text.Trim Then
                                Return
                            End If
                            SetCheckedNode(treQuyen.FocusedNode)
                        End If
                    End If
            End Select
        End If
        treQuyen.EndUpdate()
    End Sub

    Private Sub FrmCapQuyenNguoiDung_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
        If e.KeyChar = Chr(Keys.Enter) Then
            SendKeys.Send("{tab}")
        End If
    End Sub

    Private Sub BtnHuyBo_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles BtnHuyBo.ItemClick
        Me.Close()
    End Sub

    Private Sub FrmCapQuyenNguoiDung_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        'Ghi và đóng
        If (e.Modifiers = GetKeyModifide(pIdGhiVaDong) And _
           e.KeyCode = GetKeyCode2(pIdGhiVaDong)) Or _
           (e.KeyCode = GetKeyCode(pIdGhiVaDong)) Then

            If Me.btnGhiVaDong.Enabled = True And Me.btnGhiVaDong.Visibility = DevExpress.XtraBars.BarItemVisibility.Always Then
                btnGhiVaDong_ItemClick(Nothing, Nothing)
            End If
        End If
        'Huỷ bỏ (thoát)
        If (e.Modifiers = GetKeyModifide(pIdThoat) And _
            e.KeyCode = GetKeyCode2(pIdThoat)) Or _
            (e.KeyCode = GetKeyCode(pIdThoat)) Then

            BtnHuyBo_ItemClick(Nothing, Nothing)
        End If
        'Trợ giúp
        If (e.Modifiers = GetKeyModifide("INFO") And _
            e.KeyCode = GetKeyCode2("INFO")) Or _
            (e.KeyCode = GetKeyCode("INFO")) Then

            If Me.btnTroGiup.Enabled = True And Me.btnTroGiup.Visibility = DevExpress.XtraBars.BarItemVisibility.Always Then
                btnTroGiup_ItemClick(Nothing, Nothing)
            End If
        End If
    End Sub

    Private Sub btnTroGiup_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnTroGiup.ItemClick
        vMsg.Show("Chưa có thông tin trợ giúp!")
    End Sub

    Private Sub treeContents_NodeCellStyle(ByVal sender As Object, ByVal e As DevExpress.XtraTreeList.GetCustomNodeCellStyleEventArgs) Handles treQuyen.NodeCellStyle
        If vUser.CanBo.UserName <> SuperAdmin Then
            If Not vUser.KiemTraQuyen(e.Node.GetValue(treMaQuyen)) Then
                e.Appearance.ForeColor = System.Drawing.SystemColors.GrayText
            Else
                e.Appearance.ForeColor = System.Drawing.SystemColors.ControlText
            End If
        End If        
    End Sub

    Private Sub treeContents_BeforeFocusNode(ByVal sender As Object, ByVal e As DevExpress.XtraTreeList.BeforeFocusNodeEventArgs) Handles treQuyen.BeforeFocusNode
        If vUser.CanBo.UserName <> SuperAdmin Then
            If Not vUser.KiemTraQuyen(e.Node.GetValue(treMaQuyen)) Then
                e.CanFocus = False
            End If
        End If
    End Sub         
End Class

Public Class clsPermission
    Inherits DM_QUYEN
    Private _NganCam As Boolean
    Public Property NganCam() As Boolean
        Get
            Return _NganCam
        End Get
        Set(ByVal value As Boolean)
            _NganCam = value
        End Set
    End Property
End Class